package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * 订单任务处理
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;
    /**
     * 处理用户端订单超时支付的任务调度
     * 每分钟执行一次
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void processTimeoutOrder(){
        log.info("用户端订单超时支付...{}",new Date());

        //获取当前时间过去的15分钟的时间
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        //2.调用mapper获取指定条件的所有的支付超时的订单
        List<Orders> ordersList = orderMapper.getByStatusAndOrdertimeLT(Orders.PENDING_PAYMENT, time);
        //3.修改这些订单的状态为已取消状态
        if(ordersList!=null && ordersList.size()>0){
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("支付超时,自动取消");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            });
        }
    }

    /**
     * 处理管理端派送中的订单未完成的任务调度
     * 每天凌晨1点钟执行一次
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder() {
        log.info("派送中的订单未完成...{}", new Date());
        //获取当前时间过去的1小时的时间
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        //2.调用mapper获取指定条件的所有的派送中未完成的订单
        List<Orders> ordersList = orderMapper.getByStatusAndOrdertimeLT(Orders.DELIVERY_IN_PROGRESS, time);
        //3.修改这些订单的状态为已完成状态
        if (ordersList != null && ordersList.size() > 0) {
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            });
        }
    }
}
